let db// IDBDatabase;
let objectStore// IDBObjectStore;

// 打开或创建数据库
const request = indexedDB.open("myDatabase", 1);

// 创建对象存储空间及索引
request.onupgradeneeded = function (event) {
  console.log("onupgradeneeded");
  db = event.target.result;

  // 创建一个名为customers的【对象存储器】（相当于一张customers表） 以id去检索张三、李四等对象
  objectStore = db.createObjectStore("customers", { keyPath: "id" });

  // 创建索引（如果需要）索引名称+对应的对象属性名称+选项
  objectStore.createIndex("name", "name", { unique: false }); //姓名可能不唯一
  objectStore.createIndex("email", "email", { unique: true }); //邮箱绝对唯一

  //   // 数据库结构创建完毕后会触发 success 事件
  //   request.onsuccess = function (event) {
  //     console.log("数据库升级成功！");
  //   };
};

// 数据库成功打开后的回调函数
request.onsuccess = function (event) {
  console.log("onsuccess");
  db = event.target.result;

  // 开启一次事务（一堆CRUD成为一个【原子任务】：不存在完成一半的概念！）
  const transaction = db.transaction(["customers"], "readwrite");

  // 开始操作“用户表”
  objectStore = transaction.objectStore("customers");

  // 添加数据
  const customer = {
    id: 1,
    name: "John Doe",
    email: "doe@example.com",
  };

  const customer2 = {
    id: 2,
    name: "John Guava",
    email: "guava@example.com",
  };

  // 添加一个客户【对象】 任何一个CRUD操作都是异步的
  const request = objectStore.add(customer);
  const request2 = objectStore.add(customer2);

  // 操作成功时“回调”
  request.onsuccess = function (event) {
    console.log("数据已添加");
  };
  request2.onsuccess = function (event) {
    console.log("数据2已添加");
  };

  // 操作失败时【整个事务（不可分割的原子任务）】中止 => 前面的所有CRUD回滚至事务前的状态
  request.onerror = function (event) {
    console.log("插入数据失败", event.target.error);
    transaction.abort();
  };

  // 创建查询异步任务 查询key/id为1的那个对象
  const getCustomerRequest = objectStore.get(1);

  getCustomerRequest.onsuccess = function (event) {
    const result = event.target.result;
    console.log(result);
  };

  const delReq = objectStore.delete(1);
  delReq.onsuccess = function (event) {
    console.log("数据已删除");
  };

  //  The object store uses in-line keys and the key parameter was provided.
  const putRequest = objectStore.put({
    ...customer,
    email: "johndoe@example.com",
  });

  putRequest.onsuccess = (e) => {
    console.log("put请求成功", e.target.result);
  };

  putRequest.onerror = function (event) {
    console.log("数据更新失败，整个事务已回滚");
    transaction.abort();
  };

};

// 错误处理
request.onerror = function (event) {
  console.log("数据库打开失败");
};

function getAllRequest() {
  // 使用 getAll 方法获取存储空间中的所有数据
  const transaction = db.transaction(["customers"], "readwrite");
  const objectStore = transaction.objectStore("customers");

  // 使用 getAll 方法获取存储空间中的所有数据
  const getAllRequest = objectStore.getAll();

  getAllRequest.onsuccess = function (event) {
    const result = event.target.result;
    console.log(result);
  };
}
